package com.leiduoduo.oms.service;

import com.leiduoduo.oms.dao.UserDao;
import com.leiduoduo.oms.pojo.Token;
import com.leiduoduo.oms.pojo.User;
import com.leiduoduo.oms.util.WeChatUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    UserDao userDao;

    Logger logger = Logger.getLogger("controller.class");
    @Override
    public User getUserByCode(String app_code) {
        return userDao.getUserByCode(app_code);
    }

    @Override
    public boolean addUser(User user) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = simpleDateFormat.format(new Date());
        user.setCreated_at(date).setUpdated_at(date);
        log.info("添加用户==============================>"+user);
        return userDao.addUser(user);
    }

    @Override
    public List<User> getUserList() {
        return userDao.getUserList();
    }

    @Override
    public String uploadPic(MultipartFile pic, HttpServletRequest req) {
        String picId = null;
        Random random = new Random();
        if(!pic.isEmpty()){
            String path = null;
            try {
                path = ResourceUtils.getURL("classpath:").getPath() + "static/upload/";
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            System.out.println(path);
            logger.info("uploadFile path =========================>"+path);
            String oldFileName = pic.getOriginalFilename();
            logger.info("uploadFile oldName =========================>"+oldFileName);
            String prefix = FilenameUtils.getExtension(oldFileName);
            logger.info("uploadFile prefix =========================>"+prefix);
            int filesize = 5000000;
            logger.info("uploadFile size =========================>"+pic.getSize());
            if (pic.getSize()>filesize){
                return "上传文件大小不能超过5M";
            }else if(prefix.equalsIgnoreCase("jpg")||
                    prefix.equalsIgnoreCase("png")||
                    prefix.equalsIgnoreCase("jpeg")||
                    prefix.equalsIgnoreCase("pneg")){
                String fileName = System.currentTimeMillis()+random.nextInt(1000000)+"_Personal.jpg";
                logger.info("new fileName=================="+pic.getName());
                File targetFile = new File(path);
                if(!targetFile.exists()){
                    targetFile.mkdirs();
                }
                try {
                    File file = new File(path, fileName);
                    pic.transferTo(file);
                }catch (Exception e){
                    e.printStackTrace();
                    return "上传失败！";
                }
                picId=path+File.separator+fileName;
            }else{
                return "上传图片格式不正确";
            }
        }
        return "上传成功";
    }

    @Override
    public byte[] getPic(String path) {
        return this.imgArray(path);
    }

    public static byte[] imgArray(String path) {
        //字节输入流
        InputStream inputStream = null;
        //字节缓冲流数组
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try {
            inputStream = new FileInputStream(path);
            byte[] b = new byte[1024];
            int len = -1;
            //循环读取
            while ((len = inputStream.read(b)) != 1) {
                byteArrayOutputStream.write(b, 0, len);
            }
            //返回byteArrayOutputStream数组
            return byteArrayOutputStream.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                //关闭流
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
    public static OutputStream writImg(byte[]img,String path){
        //创建一个字节输出流
        OutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(path);
            //将图片输读取流中
            outputStream.write(img);
            //刷新
            outputStream.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                //关闭
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return outputStream;
    }

    @Override
    public boolean upUser(User user) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = simpleDateFormat.format(new Date());
        user.setUpdated_at(date);
        log.info("修改用户==============================>id:"+user.getId());
        return userDao.upUser(user);
    }

    @Override
    public boolean upUserToken(User user) {
        return userDao.upUserToken(user);
    }

    @Override
    public boolean delUser(User user) {
        log.info("删除id===============>"+user.getId());

        return userDao.delUser(user);
    }

    @Override
    public String createToken(String openId){
        return new Token().getToken(openId);
    }

    @Override
    public String getWeChatOpenId(String appId, String appSecret, String code) {
        // appid微信小程序ID
        // secret微信小程序秘钥
        // 根据小程序穿过来的appid/secret/code向这个url发送请求
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appId + "&secret=" + appSecret + "&js_code=" + code + "&grant_type=authorization_code";
        String str = WeChatUtil.httpRequest(url, "GET", null);
        return str;
    }

    @Override
    public User getUserByOpenId(String openId) {
        return userDao.getUserByOpenId(openId);
    }
}
